package com.sskj.level.presenter;

import com.google.gson.Gson;
import com.sskj.common.base.HttpData;
import com.sskj.common.http.WebSocketObserver;
import com.sskj.common.util.DisposUtil;
import com.sskj.level.http.HttpConfig;
import com.sskj.level.ui.fragment.FiveFragment;
import com.sskj.lib.bean.WSFiveBean;
import com.sskj.lib.http.CallBackOption;
import com.sskj.lib.util.CommonUtil;

import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


public class FiveFragmentPresenter extends BasePresenter<FiveFragment> {


    private WebSocketObserver stockSocketFive;
    private Disposable stockDisposableFive;
    private String code;

    /**
     * 盘口
     *
     * @param code 币种标识符
     * @return
     */
    public void getPankou(String code) {
        httpService.getPankou(CommonUtil.dealReuqestCode(code)).execute(new CallBackOption<HttpData<WSFiveBean>>() {
        }
                .loadBind(mView)
                .execute(httpData -> {
                    if (httpData.getStatus() == HttpConfig.OK && httpData.getData() != null) {
                        mView.updateFive(httpData.getData());
                    }
                }));
    }

    public void initSocket(String code) {
        if (code == null) {
            return;
        }
        code = CommonUtil.dealReuqestCode(code);

        if (stockSocketFive == null) {
            stockSocketFive = httpService.pushCoinFive(code);
            stockDisposableFive = stockSocketFive
                    .map(s -> new Gson().fromJson(s, WSFiveBean.class))
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(data -> {
                        mView.updateFive(data);

                    }, e -> {

                    });
        } else {
            stockSocketFive.send("{\"type\":\"buy_sell_five_lever\",\"list\":[\"" + code + "\"]}");

        }
        this.code = code;
    }

    public void sendCode(String code) {

        initSocket(code);
    }

    @Override
    public void detachView() {
        if (stockSocketFive != null) {
            stockSocketFive.close();
            stockSocketFive = null;
        }
        DisposUtil.close(stockDisposableFive);
        super.detachView();
    }


}
